<?php

namespace think\seecms\command;

use seecms\lib\Backup;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option as InputOption;
use think\console\Output;


class Database extends Command
{
    protected $help = '
Usage:    
    php think seecms:database  run               执行migrate:run命令
    php think seecms:database  seed              执行seed:run命令
    php think seecms:database  backup            执行备份
    php think seecms:database  backup --mail     将备份结果以邮件的形式发送到配置的邮箱
    php think seecms:database  backup -m         同上
';

    protected function configure()
    {
        // 指令配置
        $this->setName('seecms:database')
            ->addArgument('action', Argument::OPTIONAL, '行为')
            ->addOption('mail', 'm', InputOption::VALUE_NONE, '是否发送邮件')
            ->addOption('tables', 't', InputOption::VALUE_REQUIRED, '备份的表')
            ->setDescription('数据库操作')
            ->setHelp($this->help);
    }

    /**
     * @throws \Exception
     * @throws \Throwable
     */
    protected function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');
        $mail = $input->getOption('mail');
        $tables = $input->getOption('tables');

        if ($action === 'backup') {

            $start = microtime(true);
            $backup = new Backup();
            $backup->setTables($tables);
            $backup->setReceiveEmail($mail);
            $result = $backup->run();
            $tables = $result->getData();
            if ($tables && is_array($tables)) {
                foreach ($tables as $item) {
                    $output->writeln(sprintf(' == %s : backup complete', $item));
                }
            }
            $end = microtime(true);
            $output->writeln('');
            $output->writeln(' < comment>All Done . Took ' . sprintf(' % .4fs', $end - $start) . ' </comment > ');

        } else {
            $output->writeln($this->help);
        }

    }
}